
package com.example.testtimeserver;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * @ClassName: DiscardServerHandler
 * @Description: TODO
 * @author Michael.Pan
 * @date 2012-12-11 上午10:40:18
 */

public class TimeServerHandler extends SimpleChannelHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        // ChannelBuffer buf = (ChannelBuffer) e.getMessage();
        // Channel ch = e.getChannel();
        // Log.d("receiver", "you input: " + e.getMessage());
        // ch.write(e.getMessage());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
        Channel ch = e.getChannel();
        ch.close();
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        Channel ch = e.getChannel();
        ChannelBuffer time = ChannelBuffers.buffer(8);
        time.writeLong(System.currentTimeMillis());
        ChannelFuture future = ch.write(time);
        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel ch = future.getChannel();
                ch.close();
            }
        });
    }

}
